//
//  DFUsageTagView.swift
//  SoudafuDoctor
//
//  Created by zhh on 2022/12/1.
//  Copyright © 2022 bnyt. All rights reserved.
//

import UIKit

public class DFUsageTagView: UIView {
    public var singleSelectBlock:((String) -> Void)?
    
    public var selectIndex: Int = 0 {
        didSet {
            let btn = tagButtonArray[selectIndex]
            self.tapTagButton(btn)
        }
    }
    public var tipsLabel = UILabel()
    public var textView = UITextView()
    public var countLabel = UILabel()
    public var expandTagStr = ""
    public var remarkView = UIView()
    public var titleStr = ""
    public var mutableSelect = false  //默认单选
    public var tagViewHeightBlock:((CGFloat) -> Void)?
    public var lastView: UIView?
    public var titleLabel = UILabel()
    public var dataSource: [String] = [] {
        didSet {
            for view in self.subviews {
                view.removeFromSuperview()
            }
            
            self.initUI()
        }
    }
    
    public var tagButtonArray: [UIButton] = []
    
    public convenience init(frame: CGRect, title: String, isMutableSelect: Bool = false) {
        self.init(frame: frame)
        self.titleStr = title
        self.mutableSelect = isMutableSelect

    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI() {
        //标题
        titleLabel.textColor = UIColor(0x212121)
        titleLabel.text = titleStr
        titleLabel.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
        self.addSubview(titleLabel)
        lastView = titleLabel
        
        titleLabel.snp.makeConstraints { make in
            make.left.top.equalTo(12)
            make.height.equalTo(16)
            make.right.equalTo(-12)
        }
        //标签
        self.setupTagButton()
        
        //输入框
        remarkView.backgroundColor = UIColor(0xf7f7f7)
        remarkView.layer.masksToBounds = true
        remarkView.layer.cornerRadius = 4
        self.addSubview(remarkView)
        
        self.superview?.layoutIfNeeded()
        remarkView.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.width.equalTo(UIScreen.bnty_width - 24 - 24)
            make.top.equalTo(lastView!.snp.bottom).offset(12)
            make.height.equalTo(0)
        }
        lastView = remarkView

        //提示文字
        tipsLabel.text = "请输入\(titleStr)，20字以内"
        tipsLabel.font = .systemFont(ofSize: 12, weight: .regular)
        tipsLabel.textColor = UIColor(0x242424, alpha: 0.7)
        remarkView.addSubview(tipsLabel)
        tipsLabel.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.top.equalTo(12)
            make.height.equalTo(14)
        }
        //textview
        textView.textColor = UIColor(0x242424)
        textView.delegate = self
        textView.backgroundColor = .clear
        remarkView.addSubview(textView)
        textView.snp.makeConstraints { make in
            make.left.equalTo(tipsLabel).offset(-2)
            make.top.equalTo(tipsLabel).offset(-5)
            make.right.equalTo(tipsLabel).offset(0)
            make.bottom.equalTo(-30)
        }
        
        //数字统计
        countLabel.attributedText = self.attributedStr(oneStr: "0", TwoStr: "/20")
        countLabel.textAlignment = .right
        countLabel.font = .systemFont(ofSize: 12, weight: .medium)
        remarkView.addSubview(countLabel)
        countLabel.snp.makeConstraints { make in
            make.right.equalTo(-19)
            make.bottom.equalTo(-10)
            make.height.equalTo(14)
        }
    }
    
    func attributedStr(oneStr :String ,TwoStr:String) ->(NSMutableAttributedString){
        let attributedStr = NSMutableAttributedString(string: oneStr, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12), NSAttributedString.Key.foregroundColor:UIColor(0x242424)])
        
        attributedStr.append(NSAttributedString(string: TwoStr, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12), NSAttributedString.Key.foregroundColor:UIColor(0x242424, alpha: 0.7)]))
        
        return attributedStr
        
    }

    
    func setupTagButton() {
        for btn in tagButtonArray {
            btn.removeFromSuperview()
        }
        tagButtonArray.removeAll()
        
        let cloumnCount = 3
        
        let tempWidth = UIScreen.bnty_width - 12 * 2
        let usageTagWidth: CGFloat = tempWidth - CGFloat(12 * (cloumnCount + 1))
        
        let width = usageTagWidth / CGFloat(cloumnCount)
        let height = 26.0
        
        for (i, str) in dataSource.enumerated() {
            let row = i / cloumnCount
            let cloumn = i % cloumnCount
            
            let tagButton = UIButton(type: .custom)
            tagButton.layer.masksToBounds = true
            tagButton.layer.cornerRadius = 4
            tagButton.setBackgroundImage(UIImage.createImage(UIColor(0xC5F7E3)), for: .normal)
            tagButton.setBackgroundImage(UIImage.createImage(UIColor(0x25C787)), for: .selected)
            tagButton.titleLabel?.font = .systemFont(ofSize: 12, weight: .medium)
            tagButton.setTitle(str, for: .normal)
            tagButton.setTitleColor(.white, for: .normal)
            tagButton.tag = 201 + i
            tagButton.addTarget(self, action: #selector(tapTagButton(_ :)), for: .touchUpInside)

            self.addSubview(tagButton)
            
            tagButton.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: width, height: height))
                make.left.equalToSuperview().offset(12 + cloumn * (12 + Int(width)))
                make.top.equalToSuperview().offset(46 + row * (12 + Int(height)))
            }
            
            tagButtonArray.append(tagButton)
            lastView = tagButton
        }
        
    }
    
    @objc func tapTagButton(_ sender: UIButton) {
        if !mutableSelect {
            //单选
            for btn in tagButtonArray {
                btn.isSelected = false
            }
            
            sender.isSelected = true
            
            let text = sender.titleLabel?.text ?? ""
            
            var height = 0
            if text == expandTagStr {
                height = 84
                
            }
            remarkView.snp.updateConstraints { make in
                make.height.equalTo(height)
            }
            UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn) {
                self.layoutIfNeeded()
            }
            
            if self.singleSelectBlock != nil {
                var text = sender.titleLabel?.text ?? ""
                if text == "其他" {
                    text = ""
                }
                
                self.singleSelectBlock!(text)
            }
            
            return
        }
        
        //多选
        sender.isSelected = !sender.isSelected
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        //计算view高度
        if lastView != nil {
            let height = lastView!.frame.maxY
            var frame = self.frame
            frame.size.height = height + 12
            self.frame = frame
            
            if self.tagViewHeightBlock != nil {
                self.tagViewHeightBlock!(self.frame.height)
            }
        }
        
    }

}

extension DFUsageTagView: UITextViewDelegate {
    public func textViewDidChange(_ textView: UITextView) {
        let text = textView.text ?? ""
        self.tipsLabel.isHidden = text.count != 0
        
        if text.count > 20 {
            textView.deleteBackward()
            textView.resignFirstResponder()
            return
        }
        
        self.countLabel.attributedText = self.attributedStr(oneStr: "\(text.count)", TwoStr: "/20")
        
    }
    
    public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        let text = textView.text ?? ""
        
        if self.singleSelectBlock != nil {
            self.singleSelectBlock!(text)
        }
        
        return true
    }
}
